<?php
namespace Application\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\ResultSet\ResultSet;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
use Zend\Db\Adapter\AdapterInterface;

class UsersTable
{

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function getUsersbyId($id)
    {
        $id = (int) $id;
        $rowset = $this->tableGateway->select(array(
            'id' => $id
        ));
        $row = $rowset->current();
        if (! $row) {
            throw new \Exception("Could not find row option $id");
        }
        return $row;
    }
    public function getAdmin()
    {

        $rowset = $this->tableGateway->select(array(
            'username' => "admin"
        ));
        $row = $rowset->current();
        if (! $row) {
            throw new \Exception("Could not find row option ussername admin");
        }
        return $row;
    }


    public function fetchAll($paginated = false)
    {
        if ($paginated) {
            // create a new Select object for the table album
            $select = new Select('Users');

            // create a new result set based on the Album entity
            $resultSetPrototype = new ResultSet();
            $resultSetPrototype->setArrayObjectPrototype(new Users());
            // create a new pagination adapter object
            $paginatorAdapter = new DbSelect(
                // our configured select object
                $select,
                // the adapter to run it against
                $this->tableGateway->getAdapter(),
                // the result set to hydrate
                $resultSetPrototype);
            $paginator = new Paginator($paginatorAdapter);
            return $paginator;
        }
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }



    public function saveUsers(Users $Users)
    {
        $data = array(
            'username' => $Users->username,
            'password' => md5($Users->password)
        );

        $id = (int) $Users->id;

        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getUsersbyId($id)) {
                $this->tableGateway->update($data, array(
                    'id' => $id
                ));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }

    public function deleteUsers($id)
    {
        $this->tableGateway->delete(array(
            'id' => $id
        ));
    }
}